package com.dpj.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dpj.seckill.exception.GlobalException;
import com.dpj.seckill.mapper.OrderMapper;
import com.dpj.seckill.pojo.*;
import com.dpj.seckill.service.GoodsService;
import com.dpj.seckill.service.OrderService;
import com.dpj.seckill.service.SeckillGoodsService;
import com.dpj.seckill.service.SeckillOrderService;
import com.dpj.seckill.utils.MD5Util;
import com.dpj.seckill.utils.UUIDUtil;
import com.dpj.seckill.vo.OrderDetailVo;
import com.dpj.seckill.vo.RespBeanEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-07-05
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private  OrderMapper orderMapper;
    @Autowired
    private SeckillOrderService seckillOrderService;
    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    @Transactional
    public Order seckill(TUser user, GoodsVo good) {
        //秒杀商品库存减1
        System.out.println(good.getId());
        ValueOperations valueOperations = redisTemplate.opsForValue();

        QueryWrapper<SeckillGoods> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("goods_id",good.getId());
        SeckillGoods seckGood = seckillGoodsService.getOne(queryWrapper);
        seckGood.setStockCount(seckGood.getStockCount()-1);
       // seckillGoodsService.updateById(seckGood); 秒杀优化，进行库存减少后先判断库存是否大于0，再进行更新操作
//        boolean seckillGoodsResult = seckillGoodsService.update(new UpdateWrapper<SeckillGoods>()
//                .set("stock_count", seckGood.getStockCount())
//                .eq("id", seckGood.getId())
//                .gt("stock_count", 0));
        boolean seckillGoodsResult = seckillGoodsService.update(new UpdateWrapper<SeckillGoods>()
                .setSql("stock_count="+"stock_count-1").eq("goods_id", good.getId())
                .gt("stock_count",0));

        if(seckGood.getStockCount()<1){

            //判断是否还有库存
            valueOperations.set("isStockEmpty"+good.getId(),"0" );
            return  null;
        }

        //生成订单
        Order order=new Order();
        order.setUserId(user.getId());
        order.setGoodsId(good.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(good.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(seckGood.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        orderMapper.insert(order);
       //生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setUserId(user.getId());
        seckillOrder.setGoodsId(good.getId());
        seckillOrderService.save(seckillOrder);
        redisTemplate.opsForValue().set("order:"+user.getId()+""+good.getId(),seckillOrder);


        return order;
    }

    //订单详情
    @Override
    public OrderDetailVo detail(Long orderId) {
        if(orderId==null){
            throw new GlobalException(RespBeanEnum.ORDER_NOT_EXIST);
        }

        Order order = orderMapper.selectById(orderId);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(order.getGoodsId());
        OrderDetailVo orderDetailVo=new OrderDetailVo();
        orderDetailVo.setOrder(order);
        orderDetailVo.setGoodsVo(goodsVo);
        return orderDetailVo;


    }

    //获取秒杀地址
    @Override
    public String createPath(TUser user, Long goodsId) {
        String path=MD5Util.md5(UUIDUtil.uuid()+"123456");
        redisTemplate.opsForValue().set("seckillPath:"+user.getId()+":"+goodsId,path,
                60, TimeUnit.SECONDS);
        return path;
    }

    //校验秒杀地址
    @Override
    public boolean checkPath(TUser user, Long goodsId, String path) {
        if(user==null||goodsId<0|| StringUtils.isEmpty(path)){
            return false;
        }
        String redisPath = (String) redisTemplate.opsForValue().get("seckillPath:" + user.getId() + ":" + goodsId);
        return path.equals(redisPath);
    }

    @Override
    public boolean checkCaptcha(TUser user, Long goodsId, String captcha) {
        if(StringUtils.isEmpty(captcha)||user==null||goodsId<0){
            return false;
        }
        String redisCaptcha = (String) redisTemplate.opsForValue().get("captcha:" + user.getId() + ":" + goodsId);
        return captcha.equals(redisCaptcha);
    }


}
